package cashpointer.core.actions;

import cashpointer.core.support.ContextStore;
import com.opensymphony.xwork2.ActionSupport;
import java.sql.Connection;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Akcja testujaca polaczenie z baza danych.
 * @author wojciech topolski
 * @version 2009-03-20
 */
public class DbtestAction extends ActionSupport {
    public String execute() throws Exception {
        // Pobranie contextu Springa.
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        // Pobranie sessionFactory.
        SessionFactory sessionFactory = (SessionFactory) ctx.getBean("sessionFactory");

        // Pobranie contextStoreBean.
        ContextStore contextStoreBean = (ContextStore) ctx.getBean("contextStoreBean");

        // Ustawiam tryb wyswietlania.
        contextStoreBean.setOutputMode(true);

        try {
            try {
                // Utworzenie nowej sessji.
                Session session = sessionFactory.openSession();

                // Testuje polaczenie.
                Connection connection = session.connection();
                connection.toString();

                contextStoreBean.setMSG("Polaczenie testowe powiodlo sie.\n");
                return SUCCESS;
            }
            catch (Exception e) {
                // Pobranie wiadomosci bledu.
                Throwable cause = e.getCause();
                StringBuilder sb = new StringBuilder();
                sb.append(e.getMessage());
                sb.append("\n");
                sb.append(cause.getMessage());

                contextStoreBean.setMSG(sb.toString());
                return ERROR;
            }
        }
        catch (Exception e) {
            contextStoreBean.setMSG("Polaczenie testowe NIE powiodlo sie.\n");
            return ERROR;
        }
    }
}

